//
//  CGPoint+extension.swift
//  iUtil
//
//  Created by wendachuan on 19/3/22.
//  Copyright © 2019年 wendachuan. All rights reserved.
//

import UIKit

/// CGPoint扩展
public extension CGPoint {
    /// 从字符串构造CGPoint
    ///
    /// - parameter pointString: 1坐标字符串,格式:(0,0)
    init?(pointString: String) {
        self.init()
        do {
            let regex = try NSRegularExpression(pattern: "^\\s*\\(\\s*([0-9\\.]+)\\s*,\\s*([0-9\\.]+)\\s*\\)\\s*$", options: NSRegularExpression.Options.allowCommentsAndWhitespace)
            if let result = regex.firstMatch(in: pointString, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: pointString.count)) {
                if result.range.location != NSNotFound {
                    if result.numberOfRanges == 3 {
                        let xNSRange = result.range(at: 1)
                        let xRange = pointString.index(pointString.startIndex, offsetBy: xNSRange.location) ..< pointString.index(pointString.startIndex, offsetBy: xNSRange.location + xNSRange.length)
                        let xStr = String(pointString[xRange])
                        let x = Float(xStr)
                        if x == nil {
                            return nil
                        }

                        let yNSRange = result.range(at: 2)
                        let yRange = pointString.index(pointString.startIndex, offsetBy: yNSRange.location) ..< pointString.index(pointString.startIndex, offsetBy: yNSRange.location + yNSRange.length)
                        let yStr = String(pointString[yRange])
                        let y = Float(yStr)
                        if y == nil {
                            return nil
                        }

                        self.x = CGFloat(x!)
                        self.y = CGFloat(y!)
                    } else {
                        return nil
                    }
                } else {
                    return nil
                }
            } else {
                return nil
            }
        } catch {
            return nil
        }
    }
}
